package com.prisetree.isv.common.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSONObject;
import com.prisetree.isv.common.constant.SystemCode;
import com.prisetree.isv.request.parameter.BaseRequestParameter;
import com.prisetree.isv.request.parameter.HeaderData;
import com.prisetree.isv.request.validate.RequestValidatorChain;

public class ParamInterceptor extends HandlerInterceptorAdapter  {
	
	private final Logger logger = Logger.getLogger(ParamInterceptor.class);
	
	@Autowired
	private RequestValidatorChain validatorChain;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String userId = request.getHeader("userId");
		String token = request.getHeader("token");
		String cVersion = request.getHeader("cVersion");
		String iVersion = request.getHeader("iVersion");
		String sign = request.getHeader("sign");
		HeaderData parameter = new HeaderData();
		parameter.setUserId(userId);
		parameter.setToken(token);
		parameter.setcVersion(cVersion);
		parameter.setiVersion(iVersion);
		parameter.setSign(sign);
		// 设置参数，允许controller中通过request参数获取以上数据
		BaseRequestParameter.setHeaderData(parameter);
		// 开始校验参数
		SystemCode validateCode = validatorChain.doValidate(new BaseRequestParameter());
		logger.info("路径：" + request.getRequestURI());
		if(SystemCode.SUCCESS == validateCode)
		{
			return true;
		}
		else
		{
			response.setContentType("application/json;charset=UTF-8");
			response.setCharacterEncoding("UTF-8");
			JSONObject res = new JSONObject();
			res.put("code", validateCode.getCode());
			res.put("msg", validateCode.getDesc());
			response.getWriter().println(res.toJSONString());
			response.getWriter().flush();
			logger.error("userId=" + userId + ";" + validateCode.getCode() + "=" + validateCode.getDesc());
			return false;
		}
	}

}
